package cn.wsn2018.tools.interceptor;

import cn.wsn2018.tools.common.CommonValue;
import cn.wsn2018.tools.model.MySessionContext;
import cn.wsn2018.tools.util.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 * Created by NZX on 2018/12/18.
 */
public class SessionInterceptor implements HandlerInterceptor{
    private static final Logger logger = LoggerFactory.getLogger(SessionInterceptor.class);
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String sessionId = request.getParameter("token");
        if(sessionId!=null&&!sessionId.isEmpty()){
            //sessionid不为null
            MySessionContext myc= MySessionContext.getInstance();
            HttpSession session = myc.getSession(sessionId);
            if(session!=null&&session.getAttribute("username")!=null&&session.getAttribute("role")!=null){
                session.setMaxInactiveInterval(CommonValue.SESSION_OUT_OF_TIME);
                //logger.info("SessionMaxOverTime："+CommonValue.SESSION_OUT_OF_TIME);
                myc.addSession(session);

                //保存当前线程的用户名 或者 token，我这里直接选择了用户名
                ThreadLocal<String> localUserName = ThreadUtil.getThreadLocalUserName();
                localUserName.set( session.getAttribute("username").toString());

                return true;
            }else {
                //sessionId不为空
                //登录失败
                //System.out.println("username"+session.getAttribute("username"));
                //System.out.println("role"+session.getAttribute("role"));
                String json = JsonUtil.failedJson(CommonValue.JSON_lOGIN_FAILED);
                //String json = JsonUtil.failedJson("浏览器异常，建议关闭浏览器后重试");
                response.sendRedirect("/login.html");
                ServletUtil.getInstance().responseOperating(response,json);
                return false;
            }
        }else {
            //sessionId为空
            String json = JsonUtil.failedJson(CommonValue.JSON_NOT_LOGIN);
            response.sendRedirect("/login.html");
            ServletUtil.getInstance().responseOperating(response,json);
            return false;
        }
    }

}
